$(document).ready(function() {
	if( getUsername() != '' && getPassword() != '' ) {
		checkLogin( getUsername(), getPassword() );
	} else {
		$('#rouletteTableList').hide();
	}
});

function login() {
	checkLogin( $('#username').val(), $('#password').val() );
}

function checkLogin( username, password ) {
	$.getJSON('http://localhost:8080/WT_Roulette/rest/lobby/login?username=' + username + "&password=" + password, function(data) {
		var username = data["username"];
		var cash = data['amountOfCash'];
		if( username != null && cash != null ) {
			
			// store credentials, if not allready has been
			if( getUsername() == '' && getPassword() == '' ) {
				setId(data['playerId']);
				setLogin(username, $('#password').val());
			}
			
			logInText( username, cash );
			$('#loginSection').hide();
			$('#logoutSection').show();
			$('#rouletteTableList').show();
			return true;
		} else {
			$('#alert').html('Failed to log in, please try again');
		}
	});
	return false;
}

function logInText(username, cash){
	var logInText = "Username: " + username + "<br/>Cash: " + cash + "<br/>";
	$('#loggedOn').html(logInText).show();
}

function logout() {
	clearLogin();
	
	// delete table list from view
	$('#rouletteTableList').hide();
	
	$('#loggedOn').hide();
	$('#loginSection').show();
	$('#username').val("");
	$('#password').val("");
	$('#logoutSection').hide();
}

function joinTable(tableId) {
	$.ajax({
		type: 'POST',
		url: 'http://localhost:8080/WT_Roulette/rest/table',
		data: {
			'tableId': tableId,
			'playerId': getId()
		},
		success: function () {
			// Redirect is in rouletteTableList
		},
		error: function(result, ajaxOptions, thrownError) {
			alert("Errormessage: " + result.status);
			alert(thrownError);
		}
	});
}
